package com.example.taobaounion3.ui.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.example.taobaounion3.R;
import com.example.taobaounion3.base.baseFragment;
import com.example.taobaounion3.model.domain.Categories;
import com.example.taobaounion3.model.domain.HomePagerContent;
import com.example.taobaounion3.presenter.ICategoryPagerPresenter;
import com.example.taobaounion3.presenter.ITicketPresenter;
import com.example.taobaounion3.presenter.impl.CategoryPagePresenterlmpl;
import com.example.taobaounion3.presenter.impl.TicketPresenterlmpl;
import com.example.taobaounion3.ui.activity.TicketActivity;
import com.example.taobaounion3.ui.adapter.HomePagerContentAdapter;
import com.example.taobaounion3.ui.adapter.LooperPagerAdapt;
import com.example.taobaounion3.ui.custom.AutoLoopViewPager;
import com.example.taobaounion3.utils.Constants;
import com.example.taobaounion3.utils.LogUtils;
import com.example.taobaounion3.utils.PresenterManager;
import com.example.taobaounion3.utils.SizeUtils;
import com.example.taobaounion3.utils.ToastUtil;
import com.example.taobaounion3.view.ICategoryPagerCallback;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.utils.LogUtil;
import com.lcodecore.tkrefreshlayout.views.TbNestedScrollView;

import java.util.List;

import butterknife.BindView;

public class HomePagerFragment extends baseFragment implements ICategoryPagerCallback, HomePagerContentAdapter.OnListerItemClickListener, LooperPagerAdapt.OnlooperPageItemClickListener {
    private ICategoryPagerPresenter mCategoryPagerPresenter;
    private int mMaterialId;
    private LooperPagerAdapt mLooperPagerAdapt;
    private HomePagerContentAdapter mContentAdapter;

    @BindView(R.id.home_pager_content_list)
    public RecyclerView mContentList;

    @BindView(R.id.looper_pager)
    public AutoLoopViewPager looperPager;

    @BindView(R.id.home_pager_title)
    public TextView currentCategoryTitleTv;

    @BindView(R.id.looper_point_container)
    public LinearLayout looperPointContainer;

    @BindView(R.id.home_pager_refresh)
    public TwinklingRefreshLayout twinklingRefreshLayout;

    @BindView(R.id.home_pager_parent)
    public LinearLayout homePagerParent;

    @BindView(R.id.home_pager_header_container)
    public LinearLayout homeHeaderContainer;

    @BindView(R.id.home_pager_nested_scroller)
    public TbNestedScrollView homePagerNestedView;


    public static HomePagerFragment newInstance(Categories.DataBean category){
        HomePagerFragment homePagerFragment=new HomePagerFragment();
        Bundle bundle =new Bundle();
        bundle.putString(Constants.KEY_HOME_PAGER_TITLE,category.getTitle());
        bundle.putInt(Constants.KEY_HOME_PAGER_MATERIAL_ID,category.getId());
        homePagerFragment.setArguments(bundle);
        return homePagerFragment;
    }

    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_home_pager;
    }

    @Override
    public void onResume() {
        //可见的时候我们调用
        super.onResume();
        looperPager.startLoop();
    }

    @Override
    public void onPause() {
        super.onPause();
        //不可见的时候我们调用
        looperPager.stopLoop();
    }

    @Override
    protected void initListener() {
        mContentAdapter.setOnListerItemClickListener(this);
        mLooperPagerAdapt.setOnlooperPageItemClickListener(this);

        //观察者
        homePagerParent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //此处疑是有空指针异常
                if (homeHeaderContainer==null){
                    return;
                }
                int headerHeight=homeHeaderContainer.getMeasuredHeight();
                //LogUtils.d(HomePagerFragment.this,"headerHeight-->"+headerHeight);
                homePagerNestedView.setHeaderHeight(headerHeight);
                int measuredHeight = homePagerParent.getMeasuredHeight();
                //LogUtils.d(HomePagerFragment.this, "measuredHeight-->" + measuredHeight);
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mContentList.getLayoutParams();
                layoutParams.height = measuredHeight;
                mContentList.setLayoutParams(layoutParams);
                if (measuredHeight != 0) {
                    homePagerParent.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            }
        });
        looperPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (mLooperPagerAdapt.getDataSize()==0){
                    return;
                }
                int targetPosition =position%mLooperPagerAdapt.getDataSize();
                //切换指示器
                updateLooperIndicator(targetPosition);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }


        });
        twinklingRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                LogUtils.d(HomePagerFragment.this,"触发了Loader more...");
                //去加载更多的内容
                if (mCategoryPagerPresenter!=null) {
                    mCategoryPagerPresenter.loaderMore(mMaterialId);
                }
            }

            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
            }
        });
    }
    //切换指示器
    private void updateLooperIndicator(int targetPosition) {
        for (int i = 0; i < looperPointContainer.getChildCount(); i++) {
            View point =looperPointContainer.getChildAt(i);
            if (i==targetPosition){
                point.setBackgroundResource(R.drawable.shape_indicator_point_selected);
            }else {
                point.setBackgroundResource(R.drawable.shape_indicator_point_normal);
            }

        }
    }

    @Override
    protected void initView(View rootView) {
        //设置布局管理器
        mContentList.setLayoutManager(new LinearLayoutManager((getContext())));
        mContentList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top=5;
                outRect.bottom=5;
            }
        });
        //创建适配器
        mContentAdapter=new HomePagerContentAdapter();
        //设置适配器
        mContentList.setAdapter(mContentAdapter);
        //创建looper适配器
         mLooperPagerAdapt=new LooperPagerAdapt();
        //设置looper适配器
        looperPager.setAdapter(mLooperPagerAdapt);
        looperPager.setDuration(4000);
        //设置Refresh相关属性
        twinklingRefreshLayout.setEnableRefresh(false);
        twinklingRefreshLayout.setEnableLoadmore(true);
    }

    @Override
    protected void initpresenter() {
        mCategoryPagerPresenter= PresenterManager.getInstance().getmCategoryPagePresenter();
        mCategoryPagerPresenter.registerViewCallback(this);
    }

    @Override
    protected void loadDate() {
        Bundle arguments=getArguments();
        String title=arguments.getString(Constants.KEY_HOME_PAGER_TITLE);
        mMaterialId=arguments.getInt(Constants.KEY_HOME_PAGER_MATERIAL_ID);
        LogUtils.d(this,"title --> "+title);
        LogUtils.d(this,"materialId -->"+mMaterialId);
        //加载数据
        if (mCategoryPagerPresenter!=null){
            mCategoryPagerPresenter.getCaontentByCategoryId(mMaterialId);
        }
        if (currentCategoryTitleTv!=null) {
            currentCategoryTitleTv.setText(title);
        }

    }

    @Override
    public void onContentLoaded(List<HomePagerContent.DataBean> contents) {
        //数据列表加载到了
        mContentAdapter.setMdata(contents);

       setUpState(State.SUCCESS);
    }

    @Override
    public int getCategoryId() {
        return mMaterialId;
    }

    @Override
    public void onLoading() {

        setUpState(State.LOADING);
    }

    @Override
    public void onError() {

        setUpState(State.ERROR);
    }

    @Override
    public void onEmpty() {

        setUpState(State.EMPTY);
    }

    @Override
    public void onLoaderMoreError() {
        ToastUtil.showToast("网络异常,请稍后重试...");
        if (twinklingRefreshLayout!=null) {
            twinklingRefreshLayout.finishLoadmore();
        }
    }

    @Override
    public void onLoaderMoreEmpty() {
        ToastUtil.showToast("没有更多商品");
        if (twinklingRefreshLayout!=null) {
            twinklingRefreshLayout.finishLoadmore();
        }
    }

    @Override
    public void onLoaderMoreLoaded(List<HomePagerContent.DataBean> contents) {
        //添加到适配器数据的底部
        mContentAdapter.addData(contents);
        if (twinklingRefreshLayout!=null) {
            twinklingRefreshLayout.finishLoadmore();
        }
        ToastUtil.showToast("加载了"+contents.size()+"条数据");
    }

    @Override
    public void onLooperListLoaded(List<HomePagerContent.DataBean> contents) {
        LogUtils.d(this,"looper size-->"+contents.size() );
        mLooperPagerAdapt.setData(contents);
        //中间点%数据的size不一定对于0，所以显示的不是第一个，需要处理一下
        int dx=(Integer.MAX_VALUE/2)%contents.size();
        int targeCenterPosition=(Integer.MAX_VALUE/2)-dx;
        //设置中间点
        looperPager.setCurrentItem(targeCenterPosition);
        LogUtils.d(this,"url-->"+contents.get(0).getPict_url());
        looperPointContainer.removeAllViews();
//        GradientDrawable selectedDrawable= (GradientDrawable) getContext().getDrawable(R.drawable.shape_indicator_point_selected);
//        GradientDrawable normalDrawable= (GradientDrawable) getContext().getDrawable(R.drawable.shape_indicator_point_normal);
//        //normalDrawable.setColor(getContext().getColor(R.color.white));

        //添加点
        for (int i = 0; i < contents.size(); i++) {
            View point =new View(getContext());

            int size= SizeUtils.dip2px(getContext(),8);
            LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(size,size);
            layoutParams.leftMargin=SizeUtils.dip2px(getContext(),5);
            layoutParams.rightMargin=SizeUtils.dip2px(getContext(),5);
            point.setLayoutParams(layoutParams);
            if (i==0) {
                point.setBackgroundResource(R.drawable.shape_indicator_point_selected);
            }else {
                point.setBackgroundResource(R.drawable.shape_indicator_point_normal);
            }
            looperPointContainer.addView(point);
        }
    }

    @Override
    protected void release() {
        if (mCategoryPagerPresenter!=null){
            mCategoryPagerPresenter.unregisterViewCallback(this);
        }
    }

    @Override
    public void onItemClick(HomePagerContent.DataBean item) {
        //列表内容被点击了
        handleItemClick(item);
        LogUtils.d(this,"list item click-->"+item.getTitle());
}

    private void handleItemClick(HomePagerContent.DataBean item) {
        //处理数据
        //拿到ticketPresenter去加载数据
        String title =item.getTitle();
        String url =item.getCoupon_click_url();
        if (TextUtils.isEmpty(url)){
            url =item.getClick_url();
        }
        //图片的URL
        String cover=item.getPict_url();
        ITicketPresenter ticketPresenter=PresenterManager.getInstance().getmTicketPresenter();
        ticketPresenter.getTicket(title,url,cover);
        startActivity(new Intent(getContext(), TicketActivity.class));
    }

    @Override
    public void onLooperItemClick(HomePagerContent.DataBean item) {
        //轮播图被点击了
        handleItemClick(item);
        LogUtils.d(this,"loop item click-->"+item.getTitle());
    }
}
